package com.wing.user.controller.admin;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wing.common.utils.JsonResult;
import com.wing.common.utils.PageResult;
import com.wing.platform.feign.PlatformClient;
import com.wing.user.model.entity.CompanyInfo;
import com.wing.user.model.entity.Menu;
import com.wing.user.model.entity.Role;
import com.wing.user.model.request.CompanyInfoForm;
import com.wing.user.model.response.CompanyInfoVO;
import com.wing.user.model.response.UserVO;
import com.wing.user.service.CompanyInfoService;
import com.wing.web.annotation.RequestObjectFieldIgnore;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 *
 * @author
 */
@Validated
@Api(value = "Admin-企业基本信息管理", tags = "#/user/companyInfo")
@RestController("companyInfoController")
@RequestMapping("/user/admin/companyInfo")
@RequiredArgsConstructor
public class CompanyInfoController {

    private final CompanyInfoService companyInfoService;
    private final PlatformClient platformClient;

    @ApiOperation(value = "查询所有企业基本信息", notes = "搜索")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "第几页", defaultValue = "1", example = "1", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "limit", value = "每页多少条", defaultValue = "10", example = "10", dataType = "Integer", paramType = "query")
            ,@ApiImplicitParam(name = "sort", value="排序字段名", defaultValue = "create_time", example = "create_time", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "order", value="排序规则(asc:正序, desc:倒序)", defaultValue = "asc", example = "asc", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "licenseNo", value = "营业执照号", defaultValue = "", example = "", dataType = "String", paramType = "query")
            ,@ApiImplicitParam(name = "name", value = "名称", defaultValue = "", example = "", dataType = "String", paramType = "query")
    })
    @GetMapping("/list")
    public PageResult<CompanyInfoVO> list(
            @RequestParam(defaultValue = "1") Integer page
            ,@RequestParam(defaultValue = "10") Integer limit
            ,@RequestParam(defaultValue = "create_time") String sort
            ,@RequestParam(defaultValue = "asc") String order
            ,String licenseNo
            ,String name
    ){
        Page<CompanyInfo> pg = new Page<>(page, limit);
        Map paramMap=new HashMap();
        paramMap.put("sort",StrUtil.toUnderlineCase(sort));
        paramMap.put("order",StrUtil.toUnderlineCase(order));
        if (StringUtils.isNotBlank(licenseNo)) {
            paramMap.put("licenseNo",licenseNo);
        }
        if (StringUtils.isNotBlank(name)) {
            paramMap.put("name",name);
        }
        IPage<CompanyInfoVO> list = companyInfoService.pageList4app(pg,paramMap);
        return new PageResult<>(list.getRecords(), list.getTotal());
    }

    @GetMapping("/getCompanyInfoList")
    public JsonResult<List<CompanyInfoVO>> getCompanyInfoList(){
        List<CompanyInfoVO> infoVOList = companyInfoService.list4app(null);
        return JsonResult.success(infoVOList);
    }

    @ApiOperation(value = "添加企业基本信息", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/add")
    public JsonResult add(@Validated(CompanyInfoForm.Add.class) CompanyInfoForm companyInfoForm) {
        if (companyInfoService.add(companyInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }

    @ApiOperation(value = "添加企业基本信息", notes = "添加")
    @RequestObjectFieldIgnore({"id", "createTime", "remark"})
    @PostMapping("/addCompany")
    public JsonResult addCompany(@RequestBody CompanyInfoForm companyInfoForm) {
        if (companyInfoService.add(companyInfoForm) > 0) {
            return JsonResult.success("添加成功");
        }
        return JsonResult.fail("添加失败");
    }



    @ApiOperation(value = "修改企业基本信息", notes = "修改")
    @PutMapping("/update")
    public JsonResult update(@Validated(CompanyInfoForm.Update.class) CompanyInfoForm companyInfoForm) {
        CompanyInfo companyInfo = companyInfoService.getById(companyInfoForm.getId());
        if(companyInfo == null){
        return JsonResult.fail("修改失败！");
        }
        CopyOptions copyOptions = CopyOptions.create()
        .setEditable(CompanyInfo.class)
        .setIgnoreError(true)
        .setIgnoreNullValue(true);
        BeanUtil.copyProperties(companyInfoForm, companyInfo, copyOptions);
        if (companyInfoService.updateById(companyInfo)) {
            return JsonResult.success("修改成功！");
        }
        return JsonResult.fail("修改失败！");
    }



    @ApiOperation(value = "删除企业基本信息", notes = "删除")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "companyInfoId", value = "企业基本信息id", required = true, dataType = "Integer", paramType = "path")
    })
    @DeleteMapping("/{id}" )
    public JsonResult delete(@PathVariable("id") Long companyInfoId) {
        CompanyInfo byId = companyInfoService.getById(companyInfoId);
        if(byId!=null){
            if (byId.getIsDefault()==true){
                return JsonResult.fail("删除失败，不允许删除默认企业");
            }
            if (companyInfoService.removeById(companyInfoId)) {
                return JsonResult.success("删除成功");
            }
        }
        return JsonResult.fail("删除失败");
    }

    @ApiOperation(value = "查询行业树", notes = "搜索")
    @GetMapping("/tree")
    public JsonResult tree() {
        return  platformClient.getTreeData();
    }

    /**
     * 根据用户id返回用户信息
     */
    @GetMapping("/getCompanyInfo")
    public JsonResult<CompanyInfoVO>getUserInfo(@RequestParam("id")Long id){

        return JsonResult.success( companyInfoService.getById(id));
    }


    @GetMapping("/getCompanyInfoByName")
    public JsonResult<CompanyInfoVO>getCompanyByName(@RequestParam("name")String name){
        return JsonResult.success(companyInfoService.getCompanyByName(name));
    }

    @ApiOperation(value="检查唯一性")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name",value = "名称",required = false,dataType = "String",paramType = "query"),
            @ApiImplicitParam(name = "id",value = "id",required = false,dataType = "Long",paramType = "query")
    })
    @GetMapping("/isOnlyName")
    public JsonResult isOnlyName(@RequestParam(name = "name",required = false) String name,
                                 @RequestParam(name="id",required=false) Long id){
        QueryWrapper<CompanyInfo> queryWrapper = new QueryWrapper<>();
        if (StringUtils.isNotBlank(name)){
            queryWrapper.eq("name", name);
        }
        if (id!=null) {
            queryWrapper.ne("id", id);
        }
        int count = companyInfoService.count(queryWrapper);
        return JsonResult.success(count==0);
    }
}
